{% extends 'base.html' %}
{% load static %}
{% block content %}

<div class="container mt-4">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-gray-800">内容管理</h1>
        <div class="flex space-x-2">
            <div class="relative">
                <input type="text" id="search-input" placeholder="搜索内容..."
                       class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all w-full md:w-64">
                <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
            <a href="{% url 'add_content' %}" class="btn bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center">
                <i class="fa fa-plus mr-2"></i> 添加内容
            </a>
        </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <select id="status-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none">
                <option value="">所有状态</option>
                <option value="published">已发布</option>
                <option value="draft">草稿</option>
                <option value="archived">已归档</option>
            </select>
            <select id="category-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none">
                <option value="">所有分类</option>
                {% for category in categories %}
                <option value="{{ category.id }}">{{ category.name }}</option>
                {% endfor %}
            </select>
            <select id="author-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none">
                <option value="">所有作者</option>
                {% for author in authors %}
                <option value="{{ author.id }}">{{ author.username }}</option>
                {% endfor %}
            </select>
            <div class="relative">
                <input type="date" id="date-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none w-full">
                <i class="fa fa-calendar absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
        </div>
        <div class="mt-4 flex justify-between items-center">
            <div class="flex items-center space-x-4">
                <select id="batch-action" class="border border-gray-300 rounded-lg px-3 py-1.5 text-sm">
                    <option value="">批量操作</option>
                    <option value="delete">删除</option>
                    <option value="publish">发布</option>
                    <option value="draft">转为草稿</option>
                </select>
                <button id="apply-batch" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-3 py-1.5 rounded-lg text-sm transition-all">
                    应用
                </button>
            </div>
            <div class="text-sm text-gray-500">
                共 <span id="total-count">{{ contents.count }}</span> 条内容
            </div>
        </div>
    </div>

    <!-- 内容列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="w-10 px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="select-all" class="rounded text-primary focus:ring-primary/50">
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="title">
                            标题 <i class="fa fa-sort ml-1 text-gray-400"></i>
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="author">
                            作者 <i class="fa fa-sort ml-1 text-gray-400"></i>
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="category">
                            分类 <i class="fa fa-sort ml-1 text-gray-400"></i>
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="date">
                            发布时间 <i class="fa fa-sort ml-1 text-gray-400"></i>
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            互动数据
                        </th>
                        <th scope="col" class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="content-list">
                    {% for content in contents %}
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-4 py-4 whitespace-nowrap">
                            <input type="checkbox" class="content-checkbox rounded text-primary focus:ring-primary/50" data-id="{{ content.id }}">
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-gray-900">
                                        <a href="{% url 'content_detail' content.id %}" class="hover:text-primary transition-colors">
                                            {{ content.title|truncatechars:50 }}
                                        </a>
                                    </div>
                                    <div class="text-xs text-gray-500">
                                        {{ content.summary|truncatechars:60 }}
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-8 w-8">
                                    <img class="h-8 w-8 rounded-full object-cover" src="{{ content.author.avatar_url|default:'https://picsum.photos/200/200?random=user' }}" alt="{{ content.author.username }}头像">
                                </div>
                                <div class="ml-3">
                                    <div class="text-sm font-medium text-gray-900">{{ content.author.username }}</div>
                                    <div class="text-xs text-gray-500">{{ content.author.email }}</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                {{ content.category.name }}
                            </span>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div>{{ content.published_at|date:"Y-m-d" }}</div>
                            <div class="text-xs text-gray-400">{{ content.published_at|time:"H:i" }}</div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap">
                            {% if content.status == 'published' %}
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                                    已发布
                                </span>
                            {% elif content.status == 'draft' %}
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
                                    草稿
                                </span>
                            {% elif content.status == 'archived' %}
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">
                                    已归档
                                </span>
                            {% endif %}
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div class="flex items-center space-x-3">
                                <div class="flex items-center">
                                    <i class="fa fa-eye text-gray-400 mr-1"></i>
                                    <span>{{ content.views }}</span>
                                </div>
                                <div class="flex items-center">
                                    <i class="fa fa-heart text-red-400 mr-1"></i>
                                    <span>{{ content.likes }}</span>
                                </div>
                                <div class="flex items-center">
                                    <i class="fa fa-comment text-blue-400 mr-1"></i>
                                    <span>{{ content.comments.count }}</span>
                                </div>
                            </div>
                        </td>
                        <td class="px-4 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <a href="{% url 'edit_content' content.id %}" class="text-indigo-600 hover:text-indigo-900 mr-3">
                                <i class="fa fa-pencil mr-1"></i>编辑
                            </a>
                            <a href="#" class="text-red-600 hover:text-red-900 delete-btn" data-id="{{ content.id }}">
                                <i class="fa fa-trash mr-1"></i>删除
                            </a>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <!-- 分页 -->
        {% if is_paginated %}
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示第 <span class="font-medium">{{ page_obj.start_index }}</span> 至 <span class="font-medium">{{ page_obj.end_index }}</span> 条，共 <span class="font-medium">{{ paginator.count }}</span> 条结果
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        {% if page_obj.has_previous %}
                        <a href="?page=1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">第一页</span>
                            <i class="fa fa-angle-double-left"></i>
                        </a>
                        <a href="?page={{ page_obj.previous_page_number }}" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">上一页</span>
                            <i class="fa fa-angle-left"></i>
                        </a>
                        {% endif %}

                        {% for num in page_obj.paginator.page_range %}
                            {% if page_obj.number == num %}
                            <span class="relative inline-flex items-center px-4 py-2 border border-primary bg-primary/10 text-sm font-medium text-primary">
                                {{ num }}
                            </span>
                            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                            <a href="?page={{ num }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                                {{ num }}
                            </a>
                            {% endif %}
                        {% endfor %}

                        {% if page_obj.has_next %}
                        <a href="?page={{ page_obj.next_page_number }}" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">下一页</span>
                            <i class="fa fa-angle-right"></i>
                        </a>
                        <a href="?page={{ page_obj.paginator.num_pages }}" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">最后一页</span>
                            <i class="fa fa-angle-double-right"></i>
                        </a>
                        {% endif %}
                    </nav>
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden transform transition-all">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">确认删除</h3>
        </div>
        <div class="px-6 py-4">
            <p class="text-sm text-gray-700">你确定要删除此内容吗？此操作不可撤销。</p>
            <p class="text-sm text-gray-500 mt-2" id="delete-content-title"></p>
        </div>
        <div class="px-6 py-4 bg-gray-50 flex justify-end space-x-3">
            <button id="cancel-delete" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                取消
            </button>
            <button id="confirm-delete" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                确认删除
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 搜索功能
    const searchInput = document.getElementById('search-input');
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const rows = document.querySelectorAll('#content-list tr');

        rows.forEach(row => {
            const title = row.querySelector('td:nth-child(2) div:first-child').textContent.toLowerCase();
            if (title.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });

        // 更新计数
        const visibleRows = document.querySelectorAll('#content-list tr:not([style*="display: none"])').length;
        document.getElementById('total-count').textContent = visibleRows;
    });

    // 筛选功能
    const filters = ['status-filter', 'category-filter', 'author-filter', 'date-filter'];
    filters.forEach(filterId => {
        const filter = document.getElementById(filterId);
        filter.addEventListener('change', applyFilters);
    });

    function applyFilters() {
        const status = document.getElementById('status-filter').value;
        const category = document.getElementById('category-filter').value;
        const author = document.getElementById('author-filter').value;
        const date = document.getElementById('date-filter').value;

        const rows = document.querySelectorAll('#content-list tr');
        let visibleCount = 0;

        rows.forEach(row => {
            const statusEl = row.querySelector('td:nth-child(6) span');
            const categoryEl = row.querySelector('td:nth-child(4) span');
            const authorEl = row.querySelector('td:nth-child(3) div:first-child');
            const dateEl = row.querySelector('td:nth-child(5) div:first-child');

            const rowStatus = statusEl ? statusEl.textContent.trim().toLowerCase() : '';
            const rowCategory = categoryEl ? categoryEl.textContent.trim() : '';
            const rowAuthor = authorEl ? authorEl.textContent.trim() : '';
            const rowDate = dateEl ? dateEl.textContent.trim() : '';

            let isVisible = true;

            if (status && rowStatus !== status.toLowerCase()) isVisible = false;
            if (category && rowCategory !== category) isVisible = false;
            if (author && rowAuthor !== author) isVisible = false;
            if (date && rowDate !== date) isVisible = false;

            row.style.display = isVisible ? '' : 'none';
            if (isVisible) visibleCount++;
        });

        document.getElementById('total-count').textContent = visibleCount;
    }

    // 全选/取消全选
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.content-checkbox');

    selectAll.addEventListener('change', function() {
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 批量操作
    const batchAction = document.getElementById('batch-action');
    const applyBatch = document.getElementById('apply-batch');

    applyBatch.addEventListener('click', function() {
        const selectedAction = batchAction.value;
        const selectedCount = document.querySelectorAll('.content-checkbox:checked').length;

        if (!selectedAction) {
            alert('请选择批量操作类型');
            return;
        }

        if (selectedCount === 0) {
            alert('请先选择内容');
            return;
        }

        if (confirm(`确定要对选中的 ${selectedCount} 条内容执行"${selectedAction}"操作吗？`)) {
            // 这里应该发送AJAX请求到后端执行批量操作
            alert(`执行批量操作: ${selectedAction} (模拟操作)`);
            // 实际项目中需要添加AJAX代码
            batchAction.value = '';
        }
    });

    // 删除功能
    const deleteButtons = document.querySelectorAll('.delete-btn');
    const deleteModal = document.getElementById('delete-modal');
    const cancelDelete = document.getElementById('cancel-delete');
    const confirmDelete = document.getElementById('confirm-delete');
    let currentContentId = null;

    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            currentContentId = this.getAttribute('data-id');
            const title = this.closest('tr').querySelector('td:nth-child(2) div:first-child').textContent;
            document.getElementById('delete-content-title').textContent = `标题: ${title}`;
            deleteModal.classList.remove('hidden');
        });
    });

    cancelDelete.addEventListener('click', function() {
        deleteModal.classList.add('hidden');
    });

    confirmDelete.addEventListener('click', function() {
        if (currentContentId) {
            // 这里应该发送AJAX请求到后端删除内容
            alert(`删除内容 ID: ${currentContentId} (模拟操作)`);
            // 实际项目中需要添加AJAX代码
            deleteModal.classList.add('hidden');
        }
    });

    // 排序功能
    const sortHeaders = document.querySelectorAll('th[data-sort]');
    let currentSortField = null;
    let sortDirection = 'asc';

    sortHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const field = this.getAttribute('data-sort');

            // 切换排序方向
            if (currentSortField === field) {
                sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortField = field;
                sortDirection = 'asc';
            }

            // 更新排序图标
            sortHeaders.forEach(h => {
                const icon = h.querySelector('i');
                if (h === this) {
                    icon.className = `fa fa-sort-${sortDirection} ml-1 text-gray-600`;
                } else {
                    icon.className = `fa fa-sort ml-1 text-gray-400`;
                }
            });

            // 排序行（实际项目中应该通过API获取排序后的数据）
            const rows = Array.from(document.querySelectorAll('#content-list tr'));
            const compare = (a, b) => {
                let valueA, valueB;

                switch(field) {
                    case 'title':
                        valueA = a.querySelector('td:nth-child(2) div:first-child').textContent.toLowerCase();
                        valueB = b.querySelector('td:nth-child(2) div:first-child').textContent.toLowerCase();
                        break;
                    case 'author':
                        valueA = a.querySelector('td:nth-child(3) div:first-child').textContent.toLowerCase();
                        valueB = b.querySelector('td:nth-child(3) div:first-child').textContent.toLowerCase();
                        break;
                    case 'category':
                        valueA = a.querySelector('td:nth-child(4) span').textContent.toLowerCase();
                        valueB = b.querySelector('td:nth-child(4) span').textContent.toLowerCase();
                        break;
                    case 'date':
                        valueA = new Date(a.querySelector('td:nth-child(5) div:first-child').textContent);
                        valueB = new Date(b.querySelector('td:nth-child(5) div:first-child').textContent);
                        break;
                    default:
                        return 0;
                }

                if (sortDirection === 'asc') {
                    return valueA < valueB ? -1 : 1;
                } else {
                    return valueA > valueB ? -1 : 1;
                }
            };

            rows.sort(compare);

            // 重新添加到表格
            const tableBody = document.getElementById('content-list');
            rows.forEach(row => {
                tableBody.appendChild(row);
            });
        });
    });
});
</script>
{% endblock %}